<template>
  <div>
    <van-pull-refresh
     v-model="isLoading"
      @refresh="onRefresh"
      >
      <van-list
        v-model="loading"
        :finished="finished"
        finished-text="没有更多了"
        @load="onLoad"
        :immediate-check="false"
        offset="50">
        <ArticleItem
         v-for="item in list"
          :key="item.art_id"
          :artItem="item"
          @dislikeEv="dislikeFn"
          @reportEV='reportFn'
          @click.native="itemClickFn(item.art_id)"
          ></ArticleItem>
      </van-list>
    </van-pull-refresh>
  </div>
</template>

<script>
import ArticleItem from '../../../components/ArticleItem.vue'
import { getArticleListAPI, dislikeArticleAPI, reportArticleAPI } from '@/api'
import Notify from '@/ui/Notify.js'

// 问题一：网页刚刚打开，create和oLoad里请求同时发送，请求的都是最新的数据
// onLoad中，两次数据合并，数据重复，key重复了
// 原因：vat-list组件，组件挂载时，默认就会判定一次是否触底
// 第一次数据也是通过网络请求回来的，标签先挂载看，数据更新DOM，所以标签没有高度，list的load事件上来就触发

export default {
  name: 'ArticleList',
  props: {
    // list: Array,
    channelId: Number
  },
  data () {
    return {
      list: [], // 文章列表数组
      loading: false, // 底部加载状态
      finished: false, // 数据是否全部加载完成
      theTime: new Date().getTime(),
      isLoading: false // 顶部的加载状态
    }
  },
  components: {
    ArticleItem
  },
  async created () {
    this.getArticleListFn()
  },
  methods: {
    // 获取文章列表的请求
    async getArticleListFn () {
      const { data: res } = await getArticleListAPI({
        channelId: this.channelId,
        timestamp: this.theTime
      })

      this.list = [...this.list, ...res.data.results]
      this.theTime = res.data.pre_timestamp

      this.loading = false // 如果胡关闭底部一直是加载中的状态，下次触底就不会触发onLoad
      if (res.data.pre_timestamp === null) {
        this.finished = true
      }

      // 顶部的加载状态
      this.isLoading = false
    },
    // 底部加载事件
    onLoad () {
      if (this.list.length === 0) {
        this.loading = false
        return
      }
      this.getArticleListFn()
    },
    // 下拉刷新
    onRefresh () {
      this.list = []
      this.theTime = new Date().getTime()
      this.getArticleListFn()
    },
    // 不感兴趣处理事件
    async dislikeFn (id) {
      await dislikeArticleAPI({ artId: id })
      Notify({ type: 'success', message: '反馈不感兴趣成功' })
    },
    // 反馈文章垃圾信息
    async reportFn (id, value) {
      try {
        await reportArticleAPI({
          artId: id,
          type: value
        })
        Notify({ type: 'success', message: '举报文章成功' })
      } catch (err) {
        Notify({ type: 'warning', message: '举报失败' })
      }
    },
    // 点击跳转文章详情
    itemClickFn (id) {
      this.$router.push({
        path: `/detail?art_id=${id}`
      })
    }
  }
}
</script>
